﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MarkDownFileSplitter.Meilisearch.Control
{
    [ToolboxItem(false)]
    public partial class SearchTestControl : UserControl
    {
        private IndexInfo indexInfo;
        public SearchTestControl()
        {
            InitializeComponent();
        }

        internal void UpdateIndex(IndexInfo indexInfo)
        {
            this.indexInfo = indexInfo;
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var dr = await MeilisearchUploader.Instance.Search(indexInfo.IndexName, this.textBox1.Text, 100, 0,this.textBoxFilter.Text);
            var hits = dr["hits"] as JArray;

            this.listView1.Items.Clear();

            for (var i = 0; i < hits.Count; i++)
            {
                ListViewItem lvi = new ListViewItem((i + 1).ToString());
                lvi.SubItems.Add(hits[i].ToString());
                lvi.SubItems.Add(hits[i]["_rankingScore"].ToString());
                lvi.SubItems.Add(hits[i]["_rankingScoreDetails"].ToString());

                lvi.Tag = hits[i] as JObject;

                this.listView1.Items.Add(lvi);
            }

            if (hits.Count == 0)
            {
                MessageBox.Show("查无记录."); return;
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count == 0) { return; }
            this.textBox2.Text = this.listView1.SelectedItems[0].Tag.ToString();
        }
    }
}
